package com._54programer.ws;

import org.springframework.beans.factory.annotation.Autowired;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author SN
 * @date Created by on 2019/11/29
 * @description
 */
@Slf4j
public class WsServer {

	@Autowired
	private NSend rSend;

	/**
	 * 单例模式创建WsServer
	 */
	private static class SingletonWsServer {
		static final WsServer instance = new WsServer();
	}

	public static WsServer getInstance() {
		return SingletonWsServer.instance;
	}

	/**
	 * 初始化
	 */
	private EventLoopGroup boss;
	private EventLoopGroup worker;
	private ServerBootstrap bootstrap;
	private ChannelFuture channelFuture;

	public WsServer() {
		boss = new NioEventLoopGroup();
		worker = new NioEventLoopGroup();
		bootstrap = new ServerBootstrap();
		bootstrap.group(boss, worker).option(ChannelOption.SO_BACKLOG, 128).channel(NioServerSocketChannel.class)
				// .childOption(ChannelOption.SO_KEEPALIVE, true) //是否开启TCP底层的心跳机制
				.childHandler(new WsServerInitializer());
	}

	/**
	 * 启动
	 * 
	 * @param cluster2
	 */
	public void start(int port, boolean cluster) {
		this.channelFuture = this.bootstrap.bind(port);
		log.info("服务器启动, 端口: " + port);
	}

	/**
	 * 关闭
	 * 
	 * @Desc :
	 * @Title: shutdown
	 * @author: k1
	 * @param port
	 */

	public void shutdown(int port) {
		this.boss.shutdownGracefully();
		this.worker.shutdownGracefully();
		log.info("Ws服务器关闭, 端口: " + port);
	}

}
